package easy;

public class Solution_557 {

    public String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int startIndex = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ' ') {
                reverse(chars, startIndex, i - 1);
                startIndex = i + 1;
            }
        }
        if (startIndex < chars.length - 1) {
            reverse(chars, startIndex, chars.length - 1);
        }
        return new String(chars);
    }

    private void reverse(char[] source, int start, int end) {
        for (; start < end; start++, end--) {
            char c = source[start];
            source[start] = source[end];
            source[end] = c;
        }
    }

    public static void main(String[] args) {
        Solution_557 model = new Solution_557();
        System.out.println(model.reverseWords("Let's take LeetCode contest"));
    }
}
